package demo3;

/**
 * 单个实例中，创建两个方法，使用同一个锁对象
 */

public class Text04 {
    public static void main(String[] args) throws InterruptedException {
        Counter04  counter = new Counter04();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase1();
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("count：" + counter.count);
    }
}


class Counter04 {
    // 初始值为0
    public static int count = 0;

    // 单独定义一个对象作为锁对象用
    Object locker = new Object();

    /**
     * 累加方法
     *
     */

    public void increase () {
        // 只定义锁代码块
        synchronized (locker) {
            count++;
        }
    }

    public void increase1 () {
        // 只定义锁代码块
        synchronized (locker) {
            count++;
        }
    }
}